package com.pochogastos.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import com.pochogastos.dao.CategoriaDAO;
import com.pochogastos.model.Usuario;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class AgregarCategoria
 */
public class AgregarCategoria extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public AgregarCategoria() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Usuario u = (Usuario)request.getSession().getAttribute("USUARIO");
			if(u==null){
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login?accion=");
				rd.forward(request, response);
			}else{
				String categoria = request.getParameter("categoria").toString();
				PrintWriter out= response.getWriter();  
				JSONObject json = new JSONObject();  
				if(categoria!=null && !categoria.equalsIgnoreCase("")){
					Integer id = CategoriaDAO.getInstance().insertCategoria(categoria,u.getId());
				    json.put("id", id.toString());    
				    json.put("nombre", categoria);  
				}
				else{
					json.put("id", "-1");  
				    json.put("nombre", ""); 
				}
				out.print(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/error.jsp"); 
			request.getSession().setAttribute("ERROR", e.getMessage());
			rd.forward(request, response); 
		} 
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Usuario u = (Usuario)request.getSession().getAttribute("USUARIO");
			if(u==null){
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login?accion=");
				rd.forward(request, response);
			}else{
				String categoria = request.getParameter("categoria").toString();
				PrintWriter out= response.getWriter();  
				JSONObject json = new JSONObject();  
				if(categoria!=null && !categoria.equalsIgnoreCase("")){
					Integer id = CategoriaDAO.getInstance().insertCategoria(categoria,u.getId());
				    json.put("id", id.toString());    
				    json.put("nombre", categoria);  
				}
				else{
					json.put("id", "-1");  
				    json.put("nombre", ""); 
				}
				out.print(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/error.jsp"); 
			request.getSession().setAttribute("ERROR", e.getMessage());
			rd.forward(request, response); 
		} 
	}

}
